package com.qf.service.impl;

import com.qf.exception.CustomerException;
import com.qf.mapper.BuildingMapper;
import com.qf.mapper.RoomMapper;
import com.qf.mapper.StorageMapper;
import com.qf.pojo.Building;
import com.qf.pojo.Room;
import com.qf.pojo.Storage;
import com.qf.service.RoomService;
import com.qf.vo.RoomWithStorageVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zdl
 * @date 2025/2/14
 */
@Service
public class RoomServiceImpl implements RoomService {
    @Resource
    private RoomMapper roomMapper;
    @Resource
    private BuildingMapper buildingMapper;

    @Resource
    private StorageMapper storageMapper;
    @Override
    public List<Room> findAllRoom() {
        return roomMapper.selectAllRoom();
    }

    @Override
    @Transactional
    public int addRoom(RoomWithStorageVo roomWithStorageVo) {
        //插入前查询一下 是否有对应的建筑
        Building building = buildingMapper.selectBuildingByBid(roomWithStorageVo.getRoom().getBid());
        if (building == null){
            throw  new CustomerException("50001","房间对应的建筑不存在");
        }
        int i;
         i = roomMapper.insertRoom(roomWithStorageVo.getRoom());
        if (i == 0){
            throw  new CustomerException("50002","添加房间失败,数据有误");
        }
        // 新增room时  需要判断房间使用类型，若为储物类型  应添加对应storage表
        if (("储物").equals(roomWithStorageVo.getRoom().getRoomUse())){
            roomWithStorageVo.getStorage().setRid(roomWithStorageVo.getRoom().getRid());
            i = storageMapper.insertStorageWithRoom(roomWithStorageVo.getStorage());
        }

        return i;
    }

    @Override
    public int delBatchRoom(List<Integer> ids) {
        // 批量删除所有房间对应的存储信息
        List<Storage> storages = storageMapper.selectStorageByRid(ids);
        // 如果存储信息存在，抛出异常
        for (Storage storage : storages) {
            if (storage != null) {
                throw new CustomerException("50002", "无法删除，房间存放了物资或设备");
            }
        }
        // 执行批量删除
        return roomMapper.delRoomBatch(ids);
    }

    @Override
    public int updateRoom(Room room) {
        //查询是否有对应的建筑
        Building building = buildingMapper.selectBuildingByBid(room.getBid());
        if (building == null){
            throw  new CustomerException("50001","房间对应的建筑不存在");
        }
        return roomMapper.updateRoom(room);
    }

    @Override
    public List<Room> findAllUseRoom() {
        return roomMapper.allUseRoom();
    }
}
